package com.qq.service;

import com.qq.pojo.CODE;
import com.qq.pojo.Message;
import com.qq.pojo.MessageType;
import com.qq.pojo.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @author： Aeolia
 * @Description： TODO
 * @Date： 2021/10/17 0:29
 */
public class ClientSocket {

    private static final String HOST = "127.0.0.1";
    private static final int PORT = 8888;
    private static Socket socket;
    private static ObjectOutputStream oos;
    private static ObjectInputStream ois;

    static {
        try {
            socket = new Socket(HOST, PORT);
            oos=new ObjectOutputStream(socket.getOutputStream());
            ois=new ObjectInputStream(socket.getInputStream());
        } catch (IOException e) {
            System.out.println("连接服务器失败");
            e.printStackTrace();
        }
    }

    public static Socket getSocket() {
        return socket;
    }

    public static Message login(User loginUser) {
        // 使用Socket的流进行登录验证
        Message resultMessage = null;
        try {
            oos.writeObject(new Message(CODE.LOGIN_REQUEST, MessageType.LOGIN, loginUser));

            resultMessage = (Message) ois.readObject();
            return resultMessage;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            return resultMessage;
        }
    }

    public static void resetSocket(){
        try {
            socket = new Socket(HOST, PORT);
        oos=new ObjectOutputStream(socket.getOutputStream());
            ois = new ObjectInputStream(socket.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
